﻿#region Copyright Information

// // ****************************************************************
// // Feel free to extend or modify the code of the application to your needs. 
// // But remember do it for the Glory of our Lord Jesus Christ
// // ****************************************************************

#endregion

#region Usings

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Xml.Linq;
using Data;
using Interfaces.Persistence;
using Interfaces.Services;
using Persistence;
using Utils.ServiceLocator;

#endregion

namespace UI
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        /// <summary>
        ///     Main windows of the application.
        /// </summary>
        public MainWindow()
        {
            Initialize();

            InitializeComponent();
            // Populate the songList.
            songsList.ItemsSource =
                ServiceLocator.Instance.Get<IPersistanceManager>().GetAll().Select(songname => songname.Name);
            // Focus the mouse cursor on songName text box.
            songName.Focus();

            live.ItemsSource = null;
        }

        /// <summary>
        /// Event triggered when the text in songName text input is changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void songName_TextChanged(object sender, TextChangedEventArgs e)
        {
            foreach (object item in songsList.Items)
            {
                if (item.ToString().Contains(songName.Text))
                {
                    songsList.SelectedItem = item;
                    break;
                }
            }

            preview.ItemsSource =
                ServiceLocator.Instance.Get<IPersistanceManager>().GetSongByName(songsList.SelectedItem.ToString()).
                               Lyrics;
        }

        /// <summary>
        /// Initialize all the components.
        /// </summary>
        private static void Initialize()
        {
            string songPath = Path.Combine(Environment.CurrentDirectory, "Songs.xml");
            // If the Songs.xml does not exist then create it empty.
            if (!File.Exists(songPath))
            {
                File.Create(songPath);
            }
            // Create screen manager.
            IScreenManager screenManager = new Services.ScreenManager.ScreenManager();
            // Register screen manager.
            ServiceLocator.Instance.Register<IScreenManager>(screenManager);

            // Holds all the screens of the system.
            var screens = ServiceLocator.Instance.Get<IScreenManager>();

            string configPath = Path.Combine(Environment.CurrentDirectory, "Configuration.xml");
            // If Configuration.xml does not exist then create it.
            // It should be deployed with the application.
            if (!File.Exists(configPath))
            {
                // At start time the screen will be defaulted to the primary screen if there is only one.
                // If there are more then one then the last one will be selected.
                var configFile =
                    new XDocument(new XElement("configuration",
                                               new XElement("screenManager",
                                                            new XElement("add",
                                                                         new XAttribute("key", "screenName"),
                                                                         new XAttribute("value", screens.ScreenToUse)))));
                configFile.Save(configPath);
            }

            // Create Persistence Manager.
            IPersistanceManager persistence =
                new PersistenceManager(Directory.GetFiles(Environment.CurrentDirectory, "Songs.xml").First());

            // Register the Persistence Manager.
            ServiceLocator.Instance.Register<IPersistanceManager>(persistence);
        }

        /// <summary>
        /// Event triggered when the list of song is double-clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void songsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // If a song is selected then it will be displayed in the preview listbox.
            if (songsList.SelectedIndex != -1)
            {
                preview.ItemsSource =
                    ServiceLocator.Instance.Get<IPersistanceManager>()
                                  .GetSongByName(songsList.SelectedItem.ToString())
                                  .Lyrics;
            }
        }

        /// <summary>
        /// Event triggered when the preview listbox is double-cliecked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void preview_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // Populate the live list with the selected item in the preview list.
            live.ItemsSource = preview.SelectedItems;
        }

        private void close_Click(object sender, RoutedEventArgs routedEventArgs)
        {
            Close();
        }

        private void screens_Click(object sender, RoutedEventArgs e)
        {
            new ScreenManager().Show();
        }

        private void liveButton_Click(object sender, RoutedEventArgs e)
        {
            Screen screen = ServiceLocator.Instance.Get<IScreenManager>().ScreenToUse;

            var lyric = (LyricInfo) live.SelectedItems[0];
            if (lyric != null)
            {
                new SecondScreen(lyric.Verse)
                    {
                        WindowStartupLocation = WindowStartupLocation.Manual,
                        WindowStyle = WindowStyle.None,
                        WindowState = WindowState.Maximized,
                        Background = SystemColors.GrayTextBrush,
                        // Note: Set the top and the left corner to the screenToUse corners.
                        Top = screen.Bounds.Top,
                        Left = screen.Bounds.Left,
                        FontSize = 60
                    }.Show();
            }
        }
    }
}